#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>

int main()
{
    //创建两个有名管道，一个只负责写操作，另一个只负责读操作
    if(mkfifo("0_myfifo",0664) == -1)
    {
        if(errno != EEXIST)
        {
            perror("fail to mkfifo");
            exit(-1);
        }
    }
    if(mkfifo("0_myfifo",0664) == -1)
    {
        if(errno != EEXIST)
        {
            perror("fail to mkfifo");
            exit(-1);
        }
    }
    //打开有名管道，进行读写操作
    int fd[2] = {0};
    fd[0] = open("0_myfifo",O_WRONLY);
    fd[1] = open("1_myfifo",O_RDONLY);
	while (1)
    {
        //从终端读取数据
        char buf_w[32] = "";
        fgets(buf_w,32,stdin);
        buf_w[strlen(buf_w)-1] = '\0';
        //对有名管道0_myfifo进行写操作
        if(write(fd[0],buf_w,strlen(buf_w)) == -1)
        {
            perror("fail to read");
            exit(-1);
        }
        //对有名管道1_myfifo进行读操作
        char buf_r[32] = "";
        if(read(fd[1],buf_r,32) == -1)
        {
            perror("fail to read");
            exit(-1);
        }
        printf("buf = %s\n",buf_r);
    }
    return 0;
}